# -*- coding: UTF-8 -*-
"""
@auth:buxiangjie
@date:2023/1/22 21:25
@describe: 公共方法
"""
import functools
import os
import json
import traceback

import yaml
import PySimpleGUI


class Common:
	ROOTDIR = os.path.dirname(os.path.dirname(__file__))

	@staticmethod
	def read_json_file(file: str) -> dict:
		"""
		读取json文件转为dict格式输出
		:param file: 文件路径
		:return: 格式化后的字典
		"""

		with open(file, "r", encoding="utf8") as f:
			data = f.read()
		return json.loads(data)

	def read_yaml_data(self, path: str, filename: str) -> dict:
		"""读取yaml文件数据"""
		try:
			with open(self.ROOTDIR + f"/{path}/{filename}", 'rb') as f:
				data = f.read()
			_data = yaml.load(data, Loader=yaml.FullLoader)
			return _data
		except Exception:
			raise OSError(traceback.extract_stack())


class FuzzCommon:

	@staticmethod
	def req_op(self: object, *args, **kwargs) -> dict:
		# 判断是否存在父节点
		try:
			if kwargs["parent_node"]:
				# 判断父节点是否为list
				if isinstance(kwargs["param"][kwargs["parent_node"]], list):
					for i in kwargs["param"][kwargs["parent_node"]]:
						try:
							del i[kwargs["cur_key"]]
						except ValueError as e:
							if "list.remove(x): x not in list" in e:
								pass
							else:
								raise e
				else:
					del kwargs["param"][kwargs["parent_node"]][kwargs["cur_key"]]
			else:
				del kwargs["param"][kwargs["cur_key"]]
			kwargs["fuzz_desc"] = self.__str__()
			kwargs["fuzz_name"] = self.__class__.__name__
			return kwargs
		except Exception:
			raise OSError(traceback.extract_stack())

	@staticmethod
	def replace_op(self: object, value, *args, **kwargs) -> dict:
		# 判断是否存在父节点
		try:
			if kwargs["parent_node"]:
				# 判断父节点是否为list
				if isinstance(kwargs["parent_node"], list):
					for i in kwargs["param"][kwargs["parent_node"]]:
						i[kwargs["cur_key"]] = value
				else:
					kwargs["param"][kwargs["parent_node"]][kwargs["cur_key"]] = value
			else:
				kwargs["param"][kwargs["cur_key"]] = value
			kwargs["fuzz_desc"] = self.__str__()
			kwargs["fuzz_name"] = self.__class__.__name__
			return kwargs
		except Exception:
			raise OSError(traceback.extract_stack())


class WindowPrint:
	__instance = None
	__window: PySimpleGUI.Window = None

	def __new__(cls, *args, **kwargs):
		if cls.__instance:
			return cls.__instance
		else:
			cls.__window = args[0]
			cls.__instance = super().__new__(cls)

	def print(self, s: str):
		print(s)
		self.__window.refresh()
